import { getSiteConfig, validateAnchor, getValidAnchor, SITE_CONFIGS, type SiteConfig } from '../config/site-config'

/**
 * Anchor选择器调试工具类
 */
export class AnchorDebugger {
    /**
     * 打印当前页面的anchor信息
     */
    static debugCurrentPage(): void {
        const url = window.location.href
        const config = getSiteConfig(url)
        const validAnchor = getValidAnchor()

        console.group('🔍 Doctor Assistant - Anchor Debug Info')
        console.log('📍 Current URL:', url)
        console.log('⚙️ Matched Config:', config)
        console.log('🎯 Primary Anchor:', config.anchor)
        console.log('✅ Valid Anchor:', validAnchor)
        console.log('🔍 Anchor Element:', document.querySelector(validAnchor))

        // 检查所有可能的anchor
        const possibleAnchors = [config.anchor, 'main', '#main', '.main', '#content', '.content', '.container', '#container', 'body']

        console.log('📋 Available Anchors:')
        possibleAnchors.forEach((anchor) => {
            const exists = validateAnchor(anchor)
            const element = document.querySelector(anchor)
            console.log(`  ${exists ? '✅' : '❌'} ${anchor}`, element)
        })

        console.groupEnd()
    }

    /**
     * 测试指定的anchor选择器
     * @param anchor 要测试的anchor选择器
     */
    static testAnchor(anchor: string): void {
        const isValid = validateAnchor(anchor)
        const element = document.querySelector(anchor)

        console.group(`🧪 Testing Anchor: ${anchor}`)
        console.log('✅ Valid:', isValid)
        console.log('🔍 Element:', element)

        if (element) {
            console.log('📐 Element Size:', {
                width: element.clientWidth,
                height: element.clientHeight
            })
            console.log('📍 Element Position:', element.getBoundingClientRect())
        }

        console.groupEnd()
    }

    /**
     * 列出所有配置的网站
     */
    static listAllConfigs(): void {
        console.group('📋 All Site Configs')
        SITE_CONFIGS.forEach((config, index) => {
            console.log(`${index + 1}. ${config.name || 'Unnamed'}`)
            console.log(`   Pattern: ${config.pattern}`)
            console.log(`   Anchor: ${config.anchor}`)
            console.log(`   Enabled: ${config.enabled !== false}`)
            console.log('---')
        })
        console.groupEnd()
    }
}

/**
 * 动态anchor选择器管理器
 */
export class AnchorManager {
    private static instance: AnchorManager
    private observers: MutationObserver[] = []
    private currentAnchor: string = ''
    private callbacks: Array<(anchor: string) => void> = []

    static getInstance(): AnchorManager {
        if (!AnchorManager.instance) {
            AnchorManager.instance = new AnchorManager()
        }
        return AnchorManager.instance
    }

    /**
     * 初始化anchor管理器
     */
    init(): void {
        this.updateCurrentAnchor()
        this.setupMutationObserver()
        this.setupUrlChangeListener()
    }

    /**
     * 获取当前有效的anchor
     */
    getCurrentAnchor(): string {
        return this.currentAnchor
    }

    /**
     * 添加anchor变化回调
     */
    onAnchorChange(callback: (anchor: string) => void): void {
        this.callbacks.push(callback)
    }

    /**
     * 移除anchor变化回调
     */
    removeAnchorChangeCallback(callback: (anchor: string) => void): void {
        const index = this.callbacks.indexOf(callback)
        if (index > -1) {
            this.callbacks.splice(index, 1)
        }
    }

    /**
     * 更新当前anchor
     */
    private updateCurrentAnchor(): void {
        const newAnchor = getValidAnchor()
        if (newAnchor !== this.currentAnchor) {
            const oldAnchor = this.currentAnchor
            this.currentAnchor = newAnchor

            console.log(`[AnchorManager] Anchor changed: ${oldAnchor} -> ${newAnchor}`)

            // 通知所有回调
            this.callbacks.forEach((callback) => {
                try {
                    callback(newAnchor)
                } catch (error) {
                    console.error('[AnchorManager] Error in anchor change callback:', error)
                }
            })
        }
    }

    /**
     * 设置DOM变化监听器
     */
    private setupMutationObserver(): void {
        const observer = new MutationObserver((mutations) => {
            let shouldUpdate = false

            mutations.forEach((mutation) => {
                if (mutation.type === 'childList') {
                    // 检查是否有新的元素添加或移除
                    if (mutation.addedNodes.length > 0 || mutation.removedNodes.length > 0) {
                        shouldUpdate = true
                    }
                }
            })

            if (shouldUpdate) {
                // 延迟检查，避免频繁更新
                setTimeout(() => this.updateCurrentAnchor(), 100)
            }
        })

        observer.observe(document.body, {
            childList: true,
            subtree: true
        })

        this.observers.push(observer)
    }

    /**
     * 设置URL变化监听器
     */
    private setupUrlChangeListener(): void {
        // 监听浏览器历史变化
        const originalPushState = history.pushState
        const originalReplaceState = history.replaceState

        history.pushState = function (...args) {
            originalPushState.apply(history, args)
            setTimeout(() => AnchorManager.getInstance().updateCurrentAnchor(), 100)
        }

        history.replaceState = function (...args) {
            originalReplaceState.apply(history, args)
            setTimeout(() => AnchorManager.getInstance().updateCurrentAnchor(), 100)
        }

        // 监听popstate事件
        window.addEventListener('popstate', () => {
            setTimeout(() => this.updateCurrentAnchor(), 100)
        })
    }

    /**
     * 清理资源
     */
    destroy(): void {
        this.observers.forEach((observer) => observer.disconnect())
        this.observers = []
        this.callbacks = []
    }
}

/**
 * 便捷函数：在控制台调试当前页面的anchor
 */
export function debugAnchor(): void {
    AnchorDebugger.debugCurrentPage()
}

/**
 * 便捷函数：测试指定的anchor选择器
 */
export function testAnchor(anchor: string): void {
    AnchorDebugger.testAnchor(anchor)
}

/**
 * 便捷函数：列出所有网站配置
 */
export function listConfigs(): void {
    AnchorDebugger.listAllConfigs()
}

// 在开发环境下，将调试函数添加到全局对象，方便在控制台直接调用
if (typeof window !== 'undefined' && process.env.NODE_ENV === 'development') {
    // 将调试相关函数挂载到window对象，便于开发调试
    ;(window as any).debugAnchor = debugAnchor
    ;(window as any).testAnchor = testAnchor
    ;(window as any).listConfigs = listConfigs
    ;(window as any).AnchorDebugger = AnchorDebugger
}
